import requests;
import json;
import base64;
from io import BytesIO;
from PIL import Image;
import qiniu;
import uuid
import os;


save_folder = r"E:\home\blog\pycut2\Image-recognition-enters-the-whiteboard\testimage"
def generate_random_id():
    # 生成一个 UUID
    random_uuid = uuid.uuid4()
    # 将 UUID 转换为十六进制字符串并取前 16 位
    return random_uuid.hex[:16]


def saveImageTem(image):
    if not os.path.exists(save_folder):
        os.makedirs(save_folder)
    # 构建保存的完整图片路径
    save_path = os.path.join(save_folder, f"{generate_random_id()}.png")
    # 将图片实例保存到指定路径
    image.save(save_path)
    # 获取并打印本地图片路径（就是刚刚保存的路径）
    # print(save_path)
    return save_path



def upload_image_to_qiniu(img):
    """
    将本地图片上传到七牛云，并返回图片在七牛云的网络访问路径。

    :param image_path: 本地图片的路径，例如 "C:/Users/yourname/your_image.jpg"
    :param access_key: 七牛云的Access Key
    :param secret_key: 七牛云的Secret Key
    :param bucket_name: 七牛云的存储空间（Bucket）名称
    :return: 图片上传到七牛云后对应的网络访问路径，如果上传失败则返回None
    """

    access_key='QCCKm9oihg-7jNmKKP-MmnP8E6AZRIUvlC24uGZX';
    secret_key='7iVSCB1pJ21jDHJEOgcZyE7Hq5WgpcHTBmHgT4X8'
    bucket_name='lmt123'
    # 构建鉴权对象
    q = qiniu.Auth(access_key, secret_key)

    # 获取文件名作为上传到七牛云后的文件名（可根据实际需求调整文件名的处理方式）
    key = f"{generate_random_id()}.png"

    # 生成上传Token，用于上传时的身份验证
    token = q.upload_token(bucket_name, key)

    # 初始化上传对象
    imgurl2=saveImageTem(img)

    ret, info = qiniu.put_file(token, key, imgurl2)

    if info.status_code == 200:
        # 构造图片的网络访问路径，格式为：七牛云域名 + 文件名（存储在桶中的文件名）
        image_url = f"http://soa2cr9tw.hn-bkt.clouddn.com//{key}"
        return image_url
    else:
        print(f"图片上传失败，错误信息：{info}")
        return None





def get_image_base64(image):
    """
    将本地图片转换为Base64编码格式
    :param image_path: 本地图片的路径
    """
    if isinstance(image, Image.Image):
        buffered = BytesIO()
        image.save(buffered, optimize=True, quality=10,format="PNG")  # quality可根据实际情况调整
        img_byte = buffered.getvalue()
        img_base64 = base64.b64encode(img_byte).decode("utf-8")
        return img_base64

    return ''

def send_dingtalk_message(imageweburl,infomessage):

    """
    向钉钉发送消息的函数
    :param webhook_url: 钉钉机器人的Webhook地址
    :param message: 要发送的消息内容
    """
    # 替换成你实际的钉钉机器人Webhook地址
    webhook_url = "https://oapi.dingtalk.com/robot/send?access_token=f8edb3cbe0ef6363beee455f1ae367066541cba025b8376b18b4cf121fa6b2fd"
    headers = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }
    data = {
        "msgtype": "markdown",
        "markdown": {
            "title": f"文字:{infomessage}",
            "text": f"# {infomessage} \n\n![图片]({imageweburl})"
        },
    }
    try:
        response = requests.post(webhook_url, headers=headers, data=json.dumps(data))
        result = response.json()
        if result.get('errcode') == 0:
            print("消息成功发送到钉钉")
        else:
            print(f"消息发送失败，错误码: {result.get('errcode')}，错误信息: {result.get('errmsg')}")
    except requests.exceptions.RequestException as e:
        print(f"发送消息时出现异常: {e}")




def sendImage2dingding(img,infomessage):
    uploaded_image_url = upload_image_to_qiniu(img)
    if uploaded_image_url:
        print(f"图片已成功上传到七牛云，网络访问路径为：{uploaded_image_url}")
        send_dingtalk_message(uploaded_image_url,infomessage)
        return uploaded_image_url


def sendImage2qiniu(img):
    uploaded_image_url = upload_image_to_qiniu(img)
    return  uploaded_image_url


